<template>
  <div class="search_module">
    <div class="pcShow" >
       <el-autocomplete class="search_input" ref="input"  v-model="search_word" 
        :fetch-suggestions="querySearch"  placeholder="Search Downloads" @keyup.enter.native="loseFocus($event)"  @change="searchDataFunc" 
        @select="searchDataFunc" popper-class="autocomplete" :popper-append-to-body="false" >
          <i class="iconfont icon-search_normal" slot="prefix"  @click="searchDataFunc()"></i>
          <template slot-scope="{ item }"> 
            <p v-html="brightenKeyword(item.value, search_word)" ></p>
          </template> 
          <i class="iconfont icon-no_normal" slot="suffix"  @click="clearSearchWord()" v-show="search_word"></i>
      </el-autocomplete>
        
      <div class="search_category">
        <p  :class="{'active':category  === 'product'}"  @click="setCategory('product')">{{product}}</p>
        <p  :class="{'active':category  === 'article'}"  @click="setCategory('article')">{{article}}</p>
        <p  :class="{'active':category  === 'file'}"  @click="setCategory('file')">Download Center</p>
      </div>
      <div class="search_res" :style="'transform(100% *'+category+', 0, 0)'">
        <transition :name="transitionName" appear>
          <div  class="productContent" v-show="category  === 'product'">
            <p class="total">{{product_total}}result found</p> 
            <div v-if="product_total > 0">
              <div class="productContent">
                <ProductItem :list="product_data" ></ProductItem> 
              </div>
              <p class="table_more" @click="getMoreData()" v-show="product_data.length<product_total">
                <i class="iconfont icon-plus"></i> <span>More</span>
              </p>
            </div>
            <p v-else class="no_data">Sorry, no relevant content was found, please try another word~</p>

          </div>
        </transition>
        <transition :name="transitionName" appear>
          <div v-show="category  === 'article'">
            <p class="total">{{article_total}}result found</p>
            <div v-if="article_total > 0">
              <div v-for="item in article_data" :key="item" class="search_article" v-class="'visible'" @click="goToArticle(item)">
                <div>
                  <div class="artilce_start">
                    <p class="artilce_title">{{item.title}}</p>
                    <p class="artilce_description" v-html="item.article_editor"></p>
                    <p class="article_other">
                      <i class="iconfont icon-View_normal2"></i><span class="view_num">{{item.view_num}}</span><span>{{item.create_time}}</span>
                    </p>
                  </div>
                  
                  <p class="article_btn">
                    <span>View details</span>
                    <i class="iconfont icon-arrow_1"></i>
                  </p>
                </div>
                <p class="article_img" :style="'background-image: url('+utils.setCdnUrl() +item.image+')'"></p>
              </div>
              <p class="table_more" @click="getMoreData()" v-show="article_data.length<article_total">
                <i class="iconfont icon-plus"></i> <span>More</span>
              </p>
            </div>
            
            <p v-else class="no_data">Sorry, no relevant content was found, please try another word~</p>
          </div>
         </transition>
        <transition :name="transitionName" appear>
          <div class="download_table"  v-show="category  === 'file'">
            <div class="download_table_div">
              <p class="download_table_title">{{file_total}}result found</p>
              <el-select v-model="file_type" placeholder="Category" 
              @change="searchDataFunc()"   popper-class="download_table_select">
                <el-option v-for="item in fileTypeList"  :key="item.value"  :label="item.label"  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div v-if="file_total > 0">
              <div class="table">
                <div class="table_th"  >
                  <p class="table_name">Name</p>
                  <p class="table_version">Version</p>
                  <p class="table_ealease_date">Release Date</p>
                  <p class="table_memory_size">Memory Size</p>
                  <p class="table_category">Category</p>
                  <p class="table_download">Download</p>
                  <p class="table_expand"></p>
                </div>
                <div v-for="item in file_data" :key="item"    :class="{'details_show ': item.details_show, 'table_td ': true}" @click="isDetailsShow(item)">
                  <div class="table_td_content">
                    <p class="table_name">{{item.file_name}}</p>
                    <p class="table_version">{{item.file_no}}</p>
                    <p class="table_ealease_date">{{item.release_time}}</p>
                    <p class="table_memory_size">{{item.file_size}}</p>
                    <p class="table_category">{{item.file_type}}</p>
                    <p class="table_download" @click.stop>
                      <a target="_blank" :download="item.file_name"  :href="utils.setCdnUrl() + item.file"> <i class="iconfont icon-Download"></i></a>
                    </p>
                    <p class="table_expand">
                      <span>         
                        <i class="iconfont icon-plus"  ></i>
                      </span>
                    </p>
                  </div>
                  <div class="expand_details">
                  <p>{{item.file_description}}</p>
                  </div>

                </div>
              </div>
              <p class="table_more" @click="getMoreData()" v-show="file_data.length<file_total">
                <i class="iconfont icon-plus"></i> <span>More</span>
              </p>
            </div>
            <p v-else class="no_data">Sorry, no relevant content was found, please try another word~</p>

          </div>
         </transition>
      </div>
    </div>
    <div class="phoneShow" >
       <el-autocomplete class="search_input" ref="input_phone"  v-model="search_word" 
        :fetch-suggestions="querySearch"  placeholder="Search Downloads" @keyup.enter.native="loseFocusPhone($event)"  @change="searchDataFunc" 
        @select="searchDataFunc" popper-class="autocomplete" :popper-append-to-body="false" >
          <i class="iconfont icon-search_normal" slot="prefix"  @click="searchDataFunc()"></i>
          <template slot-scope="{ item }">
            <p v-html="brightenKeyword(item.value, search_word)" ></p>
          </template>
          <i class="iconfont icon-no_normal" slot="suffix"  @click="clearSearchWord()" v-show="search_word"></i>
      </el-autocomplete>
      <div class="search_category">
        <p  :class="{'active':category  === 'product'}"  @click="setCategory('product')">{{product}}</p>
        <p  :class="{'active':category  === 'article'}"  @click="setCategory('article')">{{article}}</p>
      </div>
      <div class="search_res" :style="'transform(100% *'+category+', 0, 0)'">
        <transition :name="transitionName" appear>
          <div  class="productContent" v-show="category  === 'product'">
            <p class="total">{{product_total}}result found</p> 
            <div v-if="product_total > 0">
              <div class="productContent">
                <div v-for="item in product_data" :key="item" class="search_product" v-class="'visible'" @click="goToProduct(item)">
                  <p class="product_img" v-if="item.data && item.data.length > 0" :style="'background-image: url('+utils.setCdnUrl() +item.data[0].image+')'"></p>
                  <p class="product_img" v-else></p>
                  <div>
                    <p class="product_title">{{item.title}}</p>
                    <p class="product_btn">
                      <span>View details</span>
                      <i class="iconfont icon-arrow_1"></i>
                    </p>
                  </div>
                </div>
              </div>
              <p class="table_more" @click="getMoreData()" v-show="product_data.length<product_total">
                <i class="iconfont icon-plus"></i> <span>More</span>
              </p>
            </div>
            <p v-else class="no_data">Sorry, no relevant content was found, please try another word~</p>
          </div>
        </transition>
        <transition :name="transitionName" appear>
          <div v-show="category  === 'article'">
            <p class="total">{{article_total}}result found</p>
            <div v-if="article_total > 0">
              <div v-for="item in article_data" :key="item" class="search_article"  v-class="'visible'" @click="goToArticle(item)">
                <p class="artilce_title">{{item.title}}</p>
                <p class="artilce_description" v-html="item.article_editor"></p>
                <p class="article_btn">
                  <span>View details</span>
                  <i class="iconfont icon-arrow_1"></i>
                </p>
              </div>
              <p class="table_more" @click="getMoreData()" v-show="article_data.length<article_total">
                <i class="iconfont icon-plus"></i> <span>More</span>
              </p>
            </div>
            <p v-else class="no_data">Sorry, no relevant content was found, please try another word~</p>
          </div>
         </transition>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getNameByMenu , formatFileSize} from '@/utils/index.js'
import { getRecommend, searchResult} from '@/api/common/personal.js'
import ProductItem from '@/components/productItem'
import { fileTypeList } from '@/api/download.js'

export default {
  data(){
    return {
      category: 'product',
      product_data: [],
      product_page: 0,
      product_total: 0,
      article_page: 0,
      article_data: [],
      article_total: 0,
      file_page: 0,
      file_data: [],
      file_total: 0,
      transitionName: '',
      recommendData: [],
      searchData:[] , //推荐搜索列表
      search_word: '',
      fileTypeList: [],
      file_type: ''
    }
  },
  components: { ProductItem },
  computed: {
    ...mapGetters(['menuArray', 'curSite', 'isPhone']),
    product(){
      return getNameByMenu(this.menuArray,'/products')
    },
    article(){
      return getNameByMenu(this.menuArray, "/community")
    }
    
  },
  watch: {
    curSite: function(){
      this.getRecommendData()
      let query = this.$route.query
      if(query) {
        this.category = query.type
        this.search_word = query.search 
        this.setSearchParams()
      }
      this.getFileTypeList()
    },
    $route: function(){
      let query = this.$route.query
      if(query) {
        this.category = query.type
        this.search_word = query.search 
        this.setSearchParams()
      }
    },
  },

  created(){
    let query = this.$route.query
    if(query) {
      this.category = query.type
      this.search_word = query.search 
      this.setSearchParams()
    }
    
    this.getRecommendData()
    this.getFileTypeList()
  },
  mounted(){

  },
  methods: {
    clearSearchWord(){
      this.search_word = '' //清空
      this.searchDataFunc()
    },
    loseFocusPhone(){
      this.$refs.input_phone.activated = false;
    },
    loseFocus() {
     this.$refs.input.activated = false;
    },
    getFileTypeList(){
      let siteID = this.curSite.id
      if(siteID){
        let params = {
          site_id: siteID
        }
        fileTypeList(params).then((res)=>{
          let list = res.data
          for(let i =0; i < list.length; i++){
            list[i].image = this.utils.setCdnUrl()()+list[i].image
          }
          this.fileTypeList = list


        })
      }
     
    },
    goToProduct(item) { //产品详情页
      this.$router.push({path: '/product/' + item.set_link})
    },
    goToArticle(item) { //文章详情页
      this.$router.push({path: '/article/' + item.link})
    },
    searchDataFunc(){ //搜索
      if(this.category == 'product'){
         this.product_page=0
      } else  if(this.category == 'article'){
         this.article_page =0
      } else  if(this.category == 'file'){
        this.file_page =0
      }
      this.setSearchParams()
    },
    getMoreData(){
      if(this.category == 'product'){
         this.product_page += 12
      } else  if(this.category == 'article'){
         this.article_page += 10
      } else  if(this.category == 'file'){
        this.file_page += 10
      }
      this.setSearchParams()
    },
    setSearchParams() {
      let siteId = this.curSite.id
      let params = {
        site_id: '',
        type: this.category ,
        key_words: this.search_word,
        page: 0
      }
      if(siteId) {
        params.site_id = siteId
        if(this.category == 'product'){
          params.page = this.product_page
        } else  if(this.category == 'article'){
          params.page = this.article_page
        } else  if(this.category == 'file'){
          params.page = this.file_page
        }
        if(this.file_type){
          params.file_type = this.file_type
        }

        this.getSearchResult(params)
      }
    },
    isDetailsShow(item){
      item.details_show = !item.details_show
    },
    getSearchResult (params){
      window.history.pushState( null,'Bonoch官网','/search?type='+params.type + '&search=' + params.key_words)
      searchResult(params).then(res=>{
        let data = res.data
        let list = data.data
        if(this.category == 'product'){
          for(let i = 0; i < list.length; i++){
             let data  = list[i].data
          if (list[i].star_comment == ''){
            list[i].star_comment = 0
          }
          if(list[i].tag_type == 1){
            list[i].tag_type = 'NEW'
          } else if(list[i].tag_type == 2){
            list[i].tag_type = 'HOT'
          } else {
            list[i].tag_type = ''
          }
          list[i].curIndex = 0
          if(data.length > 0){
            list[i].curSpec = list[i].data[0]
          } else {
            list[i].curSpec = {}
          }
          // 如果asin都不存在则不展示次产品
          let isAsinAll = 0
          for(let j = 0; j < data.length; j++) {
            if(!data[j].asin) {
              isAsinAll +=1
            }
          }
          if(isAsinAll == data.length) {
            list[i].show = false
          } else {
            list[i].show = true
          }
          }
        
          this.product_total = data.count
          if(params.page == 0){
            this.product_data = list
          } else {
            this.product_data = this.product_data.concat(list)
          }
          
        } else  if(this.category == 'article'){
          this.article_total =  data.count
          if(params.page == 0){
            this.article_data = list
          } else {
            this.article_data = this.article_data.concat(list)
          }
        } else  if(this.category == 'file'){
          for(let i in list){
            list[i].file_size = formatFileSize(list[i].file_size)
            list[i].details_show = false
          }
          this.file_total =  data.count
          if(params.page == 0){
            this.file_data = list
          } else {
            this.file_data = this.file_data.concat(list)
          }
        }

      })
    },
    brightenKeyword(val, keyword) {
      const Reg = new RegExp(keyword, 'i');
      if(val){
        return val.replace(Reg, function(match){
         return `<span class="keyword">${match}</span>`
        });
      }
    },
    querySearch(queryString, cb) {
      var fileNameList = this.recommendData;
      var results = queryString ? fileNameList.filter(this.createFilter(queryString)) : fileNameList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1);
      };
    },
    getRecommendData(){ // 推荐数据
     let siteId = this.curSite.id
      if(siteId){
        let params = {
          site_id: siteId
        }
        getRecommend(params).then(res=>{
          let list = res.data.all_key_words
          for(let i in list){
            list[i].link = '/search?type='+ list[i].type +'&search=' +list[i].label
          }
          this.search_recomend_product = res.data.product_data
          this.recommendData = JSON.parse(JSON.stringify(list)); 
          this.searchData = list.splice(0 , 6)
        })
      }
      
    },

    setCategory(index){
      if(this.category > index){
        this.transitionName = 'fade-right'
      } else {
        this.transitionName = 'fade-left'
      }
      this.category = index
      this.setSearchParams()
      window.scrollTo({
        top: 0 ,
        left: 0,
        behavior: 'smooth'
      });
    }
  }

}
</script>

<style lang="scss">
@import '@/styles/other/search.scss';
</style>